/*
 *  Copyright 2011 yuxinlei.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package com.hudson.plugin.result.collector.server.datastore.internal.dao.impl;

import com.hudson.plugin.result.collector.server.datastore.dao.HudsonsEntityJpaController;
import com.hudson.plugin.result.collector.server.datastore.dao.exceptions.NonexistentEntityException;
import com.hudson.plugin.result.collector.server.datastore.dao.exceptions.PreexistingEntityException;
import com.hudson.plugin.result.collector.server.datastore.internal.entity.*;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author yuxinlei
 */
public class HudsonsEntityJpaControllerImpl implements HudsonsEntityJpaController {

    public HudsonsEntityJpaControllerImpl() {
        emf = Persistence.createEntityManagerFactory("reportdb");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(HudsonsEntity hudsonsEntity) throws PreexistingEntityException, Exception {
        if (hudsonsEntity.getProjectsesById() == null) {
            hudsonsEntity.setProjectsesById(new ArrayList<ProjectsEntity>());
        }
        if (hudsonsEntity.getViewsesById() == null) {
            hudsonsEntity.setViewsesById(new ArrayList<ViewsEntity>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<ProjectsEntity> attachedProjectsesById = new ArrayList<ProjectsEntity>();
            if(null!=hudsonsEntity.getProjectsesById())
            for (ProjectsEntity projectsesByIdProjectsEntityToAttach : hudsonsEntity.getProjectsesById()) {
                projectsesByIdProjectsEntityToAttach = em.getReference(projectsesByIdProjectsEntityToAttach.getClass(), projectsesByIdProjectsEntityToAttach.getId());
                attachedProjectsesById.add(projectsesByIdProjectsEntityToAttach);
            }
            hudsonsEntity.setProjectsesById(attachedProjectsesById);
            Collection<ViewsEntity> attachedViewsesById = new ArrayList<ViewsEntity>();
            if(null!=hudsonsEntity.getViewsesById())
            for (ViewsEntity viewsesByIdViewsEntityToAttach : hudsonsEntity.getViewsesById()) {
                viewsesByIdViewsEntityToAttach = em.getReference(viewsesByIdViewsEntityToAttach.getClass(), viewsesByIdViewsEntityToAttach.getId());
                attachedViewsesById.add(viewsesByIdViewsEntityToAttach);
            }
            hudsonsEntity.setViewsesById(attachedViewsesById);
            em.persist(hudsonsEntity);
            if(null!=hudsonsEntity.getProjectsesById())
            for (ProjectsEntity projectsesByIdProjectsEntity : hudsonsEntity.getProjectsesById()) {
                HudsonsEntity oldHudsonsByHudsonIdOfProjectsesByIdProjectsEntity = projectsesByIdProjectsEntity.getHudsonsByHudsonId();
                projectsesByIdProjectsEntity.setHudsonsByHudsonId(hudsonsEntity);
                projectsesByIdProjectsEntity = em.merge(projectsesByIdProjectsEntity);
                if (oldHudsonsByHudsonIdOfProjectsesByIdProjectsEntity != null) {
                    oldHudsonsByHudsonIdOfProjectsesByIdProjectsEntity.getProjectsesById().remove(projectsesByIdProjectsEntity);
                    oldHudsonsByHudsonIdOfProjectsesByIdProjectsEntity = em.merge(oldHudsonsByHudsonIdOfProjectsesByIdProjectsEntity);
                }
            }
            if(null!=hudsonsEntity.getViewsesById())
            for (ViewsEntity viewsesByIdViewsEntity : hudsonsEntity.getViewsesById()) {
                HudsonsEntity oldHudsonsByHudsonIdOfViewsesByIdViewsEntity = viewsesByIdViewsEntity.getHudsonsByHudsonId();
                viewsesByIdViewsEntity.setHudsonsByHudsonId(hudsonsEntity);
                viewsesByIdViewsEntity = em.merge(viewsesByIdViewsEntity);
                if (oldHudsonsByHudsonIdOfViewsesByIdViewsEntity != null) {
                    oldHudsonsByHudsonIdOfViewsesByIdViewsEntity.getViewsesById().remove(viewsesByIdViewsEntity);
                    oldHudsonsByHudsonIdOfViewsesByIdViewsEntity = em.merge(oldHudsonsByHudsonIdOfViewsesByIdViewsEntity);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findHudsonsEntity(hudsonsEntity.getId()) != null) {
                throw new PreexistingEntityException("HudsonsEntity " + hudsonsEntity + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(HudsonsEntity hudsonsEntity) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            HudsonsEntity persistentHudsonsEntity = em.find(HudsonsEntity.class, hudsonsEntity.getId());
            Collection<ProjectsEntity> projectsesByIdOld = persistentHudsonsEntity.getProjectsesById();
            Collection<ProjectsEntity> projectsesByIdNew = hudsonsEntity.getProjectsesById();
            Collection<ViewsEntity> viewsesByIdOld = persistentHudsonsEntity.getViewsesById();
            Collection<ViewsEntity> viewsesByIdNew = hudsonsEntity.getViewsesById();
            Collection<ProjectsEntity> attachedProjectsesByIdNew = new ArrayList<ProjectsEntity>();
            if(projectsesByIdNew!=null)
            for (ProjectsEntity projectsesByIdNewProjectsEntityToAttach : projectsesByIdNew) {
                projectsesByIdNewProjectsEntityToAttach = em.getReference(projectsesByIdNewProjectsEntityToAttach.getClass(), projectsesByIdNewProjectsEntityToAttach.getId());
                attachedProjectsesByIdNew.add(projectsesByIdNewProjectsEntityToAttach);
            }
            projectsesByIdNew = attachedProjectsesByIdNew;
            hudsonsEntity.setProjectsesById(projectsesByIdNew);
            Collection<ViewsEntity> attachedViewsesByIdNew = new ArrayList<ViewsEntity>();
            if(viewsesByIdNew!=null)
            for (ViewsEntity viewsesByIdNewViewsEntityToAttach : viewsesByIdNew) {
                viewsesByIdNewViewsEntityToAttach = em.getReference(viewsesByIdNewViewsEntityToAttach.getClass(), viewsesByIdNewViewsEntityToAttach.getId());
                attachedViewsesByIdNew.add(viewsesByIdNewViewsEntityToAttach);
            }
            viewsesByIdNew = attachedViewsesByIdNew;
            hudsonsEntity.setViewsesById(viewsesByIdNew);
            hudsonsEntity = em.merge(hudsonsEntity);
            if(null!=projectsesByIdOld)
            for (ProjectsEntity projectsesByIdOldProjectsEntity : projectsesByIdOld) {
                if (!projectsesByIdNew.contains(projectsesByIdOldProjectsEntity)) {
                    projectsesByIdOldProjectsEntity.setHudsonsByHudsonId(null);
                    projectsesByIdOldProjectsEntity = em.merge(projectsesByIdOldProjectsEntity);
                }
            }
            if(projectsesByIdNew!=null)
            for (ProjectsEntity projectsesByIdNewProjectsEntity : projectsesByIdNew) {
                if (!projectsesByIdOld.contains(projectsesByIdNewProjectsEntity)) {
                    HudsonsEntity oldHudsonsByHudsonIdOfProjectsesByIdNewProjectsEntity = projectsesByIdNewProjectsEntity.getHudsonsByHudsonId();
                    projectsesByIdNewProjectsEntity.setHudsonsByHudsonId(hudsonsEntity);
                    projectsesByIdNewProjectsEntity = em.merge(projectsesByIdNewProjectsEntity);
                    if (oldHudsonsByHudsonIdOfProjectsesByIdNewProjectsEntity != null && !oldHudsonsByHudsonIdOfProjectsesByIdNewProjectsEntity.equals(hudsonsEntity)) {
                        oldHudsonsByHudsonIdOfProjectsesByIdNewProjectsEntity.getProjectsesById().remove(projectsesByIdNewProjectsEntity);
                        oldHudsonsByHudsonIdOfProjectsesByIdNewProjectsEntity = em.merge(oldHudsonsByHudsonIdOfProjectsesByIdNewProjectsEntity);
                    }
                }
            }
            if(null!=viewsesByIdOld)
            for (ViewsEntity viewsesByIdOldViewsEntity : viewsesByIdOld) {
                if (!viewsesByIdNew.contains(viewsesByIdOldViewsEntity)) {
                    viewsesByIdOldViewsEntity.setHudsonsByHudsonId(null);
                    viewsesByIdOldViewsEntity = em.merge(viewsesByIdOldViewsEntity);
                }
            }
            if(null!=viewsesByIdNew)
            for (ViewsEntity viewsesByIdNewViewsEntity : viewsesByIdNew) {
                if (!viewsesByIdOld.contains(viewsesByIdNewViewsEntity)) {
                    HudsonsEntity oldHudsonsByHudsonIdOfViewsesByIdNewViewsEntity = viewsesByIdNewViewsEntity.getHudsonsByHudsonId();
                    viewsesByIdNewViewsEntity.setHudsonsByHudsonId(hudsonsEntity);
                    viewsesByIdNewViewsEntity = em.merge(viewsesByIdNewViewsEntity);
                    if (oldHudsonsByHudsonIdOfViewsesByIdNewViewsEntity != null && !oldHudsonsByHudsonIdOfViewsesByIdNewViewsEntity.equals(hudsonsEntity)) {
                        oldHudsonsByHudsonIdOfViewsesByIdNewViewsEntity.getViewsesById().remove(viewsesByIdNewViewsEntity);
                        oldHudsonsByHudsonIdOfViewsesByIdNewViewsEntity = em.merge(oldHudsonsByHudsonIdOfViewsesByIdNewViewsEntity);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                int id = hudsonsEntity.getId();
                if (findHudsonsEntity(id) == null) {
                    throw new NonexistentEntityException("The hudsonsEntity with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(int id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            HudsonsEntity hudsonsEntity;
            try {
                hudsonsEntity = em.getReference(HudsonsEntity.class, id);
                hudsonsEntity.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The hudsonsEntity with id " + id + " no longer exists.", enfe);
            }
            Collection<ProjectsEntity> projectsesById = hudsonsEntity.getProjectsesById();
            if(null!=projectsesById)
            for (ProjectsEntity projectsesByIdProjectsEntity : projectsesById) {
                projectsesByIdProjectsEntity.setHudsonsByHudsonId(null);
                projectsesByIdProjectsEntity = em.merge(projectsesByIdProjectsEntity);
            }
            Collection<ViewsEntity> viewsesById = hudsonsEntity.getViewsesById();
            if(null!=viewsesById)
            for (ViewsEntity viewsesByIdViewsEntity : viewsesById) {
                viewsesByIdViewsEntity.setHudsonsByHudsonId(null);
                viewsesByIdViewsEntity = em.merge(viewsesByIdViewsEntity);
            }
            em.remove(hudsonsEntity);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }


    public HudsonsEntity findHudsonsEntity(int id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(HudsonsEntity.class, id);
        } finally {
            em.close();
        }
    }

    public List<Integer> findHudsonsEntity(String url) {
        EntityManager em = getEntityManager();
        try {
            Query query = em.createNativeQuery("select h.id from hudsons h where h.url =:url"  );
            query.setParameter("url", url.trim());
            List<Integer> hudsonsIds = query.getResultList();
            return hudsonsIds;
        } finally {
            em.close();
        }
    }


public List<HudsonsEntity> findHudsonsEntityEntities() {
        return findHudsonsEntityEntities(true, -1, -1);
    }

    public List<HudsonsEntity> findHudsonsEntityEntitiesWithInterval(boolean isAverage, int resultsInterval, int firstResult) {
        return findHudsonsEntityEntities(true, -1, -1);
    }

    public List<HudsonsEntity> findHudsonsEntityEntities(int maxResults, int firstResult) {
        return findHudsonsEntityEntities(false, maxResults, firstResult);
    }

    private List<HudsonsEntity> findHudsonsEntityEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(HudsonsEntity.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }



    public int getHudsonsEntityCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<HudsonsEntity> rt = cq.from(HudsonsEntity.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }


}
